<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <div class="area-header">
        <span class="area-header-title">{{ $t('基金基本信息') }}</span>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('公司全称')" prop="fundFullName">
            <el-autocomplete
              v-model="form.fundFullName"
              class="inline-input name"
              :fetch-suggestions="fundQuerySearch"
              :placeholder="$t('公司全称')"
              :trigger-on-focus="false"
              :maxlength="100"
              @select="fundHandleSelect"
            >
              <template v-if="enableTyc" slot="append">
                <a @click="fundHandleSelect">{{ $t('查询工商信息') }}</a>
              </template>
            </el-autocomplete>
            <!--            <el-input v-else v-model="form.fundFullName" readonly show-word-limit maxlength="100">
              <template slot="append" @click="fundHandleSelect">
                <a @click="fundHandleSelect">{{ $t('查询工商信息') }}</a>
              </template>
            </el-input>-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('公司简称')" prop="fundName">
            <el-input v-model="form.fundName" :placeholder="$t('公司简称')" show-word-limit :maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('负责人')" prop="personCharge">
            <user-select v-model="form.personCharge" :placeholder="$t('负责人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('币种')" prop="currency">
            <dictSelect
              v-model="form.currency"
              :clearable="true"
              dictionary="currency"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('设立日期')" prop="foundationDate">
            <DatePicker
              v-model="form.foundationDate"
              :placeholder="$t('设立日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('企业统一社会信用代码')" prop="creditCode">
            <el-input v-model="form.creditCode" placeholder="企业统一社会信用代码" show-word-limit maxlength="20" />
          </el-form-item>
        </el-col>
        <Area ref="cityZj" :buss-data="form" />
        <el-col :span="12">
          <el-form-item :label="$t('管理方式')" prop="fundBaseSpv.managementMode">
            <el-select v-model="form.fundBaseSpv.managementMode" :placeholder="$t('管理方式')">
              <el-option
                v-for="item in spvManageModeOption"
                :key="item.dictValue"
                :value="item.dictValue"
                :label="$t(item.dictLabel)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('执行事务合伙人')" prop="fundBaseSpv.executivePartner">
            <el-select v-model="form.fundBaseSpv.executivePartner" :placeholder="$t('从SPV出资人中选择')" :disabled="!form.id">
              <el-option
                v-for="item in executivePartnerOption"
                :key="item.id"
                :value="item.id"
                :label="item.userName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('管理人')" prop="managerId">
            <MainBodySelect
              v-model="form.managerId"
              :parameters="!managerOpen ? 'manager' : ''"
              style="float: left; width: 100%;z-index: 1000 !important;"
            />
            <div class="addGLR" @click="addManager">
              <span class="addGLRText">{{ $t('添加管理人') }}</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('GP')" prop="fundBaseSpv.gpIds">
            <el-select v-model="form.gpIds" multiple filterable :placeholder="$t('请选择')">
              <el-option
                v-for="item in gpBaseOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('法律形式')" prop="legalForm">
            <dict-select
              v-model="form.fundBaseSpv.legalForm"
              dictionary="legal_form"
              :placeholder="$t('法律形式')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="area-header">
        <span class="area-header-title">{{ $t('基金期限') }}</span>
      </div>
      <el-table
        :data="form.fundPhaseList"
        border
        class="nowrapTable formTable"
      >
        <el-table-column prop="phase" :label="$t('阶段')">
          <template slot-scope="scope">
            <el-form-item :prop="'fundPhaseList.' + scope.$index + '.phase'">
              <dictSelect
                v-model="scope.row.phase"
                :clearable="true"
                dictionary="fund_phase"
                @change="phaseChange($event, scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="year" :label="$t('期限(年)')">
          <template slot-scope="scope">
            <el-form-item prop="year">
              <el-input-number v-model="scope.row.year" :precision="1" :min="0" :max="1000" :placeholder="$t('期限(年)')" @change="yearChange(scope.row, scope.$index)" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" :label="$t('起始日期')">
          <template slot-scope="scope">
            <el-form-item prop="startDate">
              <DatePicker
                v-model="scope.row.startDate"
                type="date"
                :placeholder="$t('起始日期')"
                @change="startDateChange(scope.row, scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="endDate" :label="$t('结束日期')">
          <template slot-scope="scope">
            <el-form-item prop="endDate">
              <DatePicker
                v-model="scope.row.endDate"
                :placeholder="$t('结束日期')"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('计提基数')" prop="accrualBase">
          <template slot-scope="scope">
            <el-form-item prop="accrualBase">
              <dict-select
                v-model="scope.row.accrualBase"
                dictionary="accrual_base"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('管理费比例(%)')" prop="managementFeeRatio">
          <template slot-scope="scope">
            <el-form-item prop="managementFeeRatio">
              <Ratio v-model="scope.row.managementFeeRatio" :controls="false" :min="0" :max="100" :precision="2" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="delFundPhase(scope.$index)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addFundPhase">{{ $t("添加") }}</el-button>
      </div>

      <FileTable :list.sync="form.fileList" data-type="fund_base" :business-type="'spv'" :business-id="$route.query.id === undefined ? form.id : $route.query.id" :btn-show="!otherBtnHide" />
      <!-- 快速添加管理人 -->
      <el-dialog :title="$t('基金管理人')" :visible.sync="managerOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
        <gpBaseForm ref="gpBaseForm" @successSaveManager="successSaveManager" />
      </el-dialog>
    </el-form>
    <div v-show="!btnHide" slot="footer" class="dialog-footer" style="text-align: center; margin-top: 10px;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn v-if="btnShow" has-permi="fund:fundbase" :cancel-show="openLocation === undefined" />
    </div>
  </div>
</template>
<script>
import { saveFundBase, getFundBase, fundInfoByFundName, fundInfoByFundFullName, fundDetailsByName, fundListByName } from '@/api/fund/fundBase'
// 省市组件
import Area from '@/components/Area'
import MainBodySelect from '@/components/MainBodySelect'
import gpBaseForm from '@/views/fund/gpBase/gpBaseForm.vue'
import { findTrueGp } from '@/api/fund/gp/gpBase'
import { findInvestByFundId } from '@/api/fund/investor/fundInvestor'
export default {
  components: {
    Area,
    gpBaseForm,
    MainBodySelect
  },
  props: {
    fundBaseData: {
      type: Array,
      default: () => []
    },
    btnShow: {
      type: Boolean,
      default: true,
      desc: '是否展示按钮'
    }
  },
  data() {
    return {
      // 是否隐藏保存等按钮
      btnHide: false,
      // 表单参数
      form: {
        fundBaseSpv: {},
        fileList: []
      },
      // 基金状态是否可以修改
      fundStatusModify: false,
      // 遮罩层
      loading: false,
      // 基金投资方式字典
      investmentWayOption: [],
      // GP管理人
      gpBaseOptions: [],
      // 管理方式
      spvManageModeOption: [],
      // 出资人
      executivePartnerOption: [],
      // 天眼查查询条件
      tycParam: {
        id: '',
        fundFullName: '',
        tycId: ''
      },
      // 表单校验
      rules: {
        fundName: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' },
          { validator: this.checkFundName, trigger: 'blur' }
        ],
        fundFullName: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' },
          { validator: this.checkFundFullName, trigger: 'blur' }
        ],
        currency: [
          { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
        ],
        personCharge: [
          { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
        ],
        managerId: [
          { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
        ],
        foundationDate: [
          { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
        ],
        'fundBaseSpv.managementMode': { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
      },
      openLocation: undefined,
      otherBtnHide: false,
      managerOpen: false,
      enableTyc: undefined
    }
  },
  watch: {
    fundBaseData: function() {
      this.form = this.fundBaseData
    }
  },
  mounted() {
    this.$bus.$emit('async_done')
    this.enableTyc = (window.localStorage.getItem('enableTyc') === 'true')
  },
  created() {
    this.getDicts('fund_nvestment_way').then(response => {
      this.investmentWayOption = response.data
    })
    this.getDicts('spv_manage_mode').then(response => {
      this.spvManageModeOption = response.data
    })
    // 查询GP管理人类型为GP
    findTrueGp().then(response => {
      this.gpBaseOptions = response.data
    })
  },
  methods: {
    // 初始化数据
    async init(data) {
      this.loading = true
      if (data !== undefined && data.id !== null && data.id !== undefined) {
        getFundBase(data.id).then(response => {
          this.form = response.data
          if (!this.form.fundBaseSpv) {
            this.form.fundBaseSpv = {}
          }
          this.$nextTick(() => {
            if (this.$refs.cityZj?.initCity !== undefined) {
              this.$refs.cityZj.initCity()
              this.$refs.cityZj.initDistrict()
            }
          })
          findInvestByFundId(this.form.id).then(res => {
            this.executivePartnerOption = res.data
          })
          this.loading = false
        })
      } else {
        this.reset()
        this.$nextTick(() => {
          if (this.$refs.cityZj?.initCity !== undefined) {
            this.$refs.cityZj.initCity()
              this.$refs.cityZj.initDistrict()
          }
        })
        // 初始化阶段数据
        this.initPhaseData()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fundName: undefined,
        fundNamePinyin: undefined,
        gpIds: [],
        creditCode: undefined,
        sCode: undefined,
        provinceRegistered: undefined,
        cityRegistered: undefined,
        registeredAddress: undefined,
        foundationDate: undefined,
        duration: undefined,
        investmentPeriod: undefined,
        dueDate: undefined,
        settlingDate: undefined,
        investOriginDate: undefined,
        investDueDate: undefined,
        extensionPeriod: undefined,
        extensionOriginDate: undefined,
        extensionDueDate: undefined,
        currency: undefined,
        investmentMode: undefined,
        fileList: [],
        dataType: 'spv',
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        legalForm: undefined,
        remark: undefined,
        delFlag: undefined,
        personCharge: undefined,
        fundPhaseList: [],
        fundBaseSpv: {
          managementMode: undefined,
          executivePartner: undefined
        }
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      // 刷新list页面
      this.$parent.$parent.getList()
      if (this.$parent.$parent.getViewList !== undefined) {
        this.$parent.$parent.getViewList()
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveFundBase(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              // 如果是通过基金home页面的路由打开，保存时不调用刷新list页面的方法
              if (this.$parent.$parent.homeOpen) {
                this.$parent.$parent.homeOpen = false
              } else if (this.openLocation === 'Home') {
                // 基金里边保存
                this.loading = false
              } else {
                this.closeForm()
                this.reset()
              }
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 校验基金简称是否存在重复
    async checkFundName(rule, value, callback) {
      if (this.form.fundName.trim() === '') {
        callback(new Error(this.$t('请输入公司简称')))
      }
      var fundList = await fundInfoByFundName(this.form.fundName)
      if ((fundList.data.length > 0 && this.form.id === undefined) || (fundList.data.length > 1 && this.form.id !== undefined)) {
        callback(new Error(this.$t('公司简称不能重复')))
      } else {
        callback()
      }
    },
    // 校验基金全称是否存在重复
    async checkFundFullName(rule, value, callback) {
      if (this.form.fundFullName.trim() === '') {
        callback(new Error(this.$t('请输入公司全称')))
      }
      var fundList = await fundInfoByFundFullName(this.form.fundFullName)
      if ((fundList.data.length > 0 && this.form.id === undefined) || (fundList.data.length > 1 && this.form.id !== undefined)) {
        callback(new Error(this.$t('公司全称不能重复')))
      } else {
        callback()
      }
    },
    // 天眼查查询
    fundQuerySearch(queryString, cb) {
      fundListByName(queryString).then(res => {
        if (res.code === 200) {
          cb(res.data)
        }
      })
    },
    formCleaing() {
      this.form.fundName = ''
      this.form.creditCode = ''
      this.form.foundationDate = ''
      this.form.provinceRegistered = ''
      this.form.cityRegistered = ''
      this.form.tycId = ''
      this.form.logoInfo = ''
    },
    // 基金选择后事件
    fundHandleSelect(item) {
      var fundFullName = this.form.fundFullName
      if (fundFullName === '' || fundFullName === undefined) {
        this.msgError(this.$t('请先输入公司全称!'))
        return
      }
      this.formCleaing()
      this.tycParam.id = this.form.id
      this.tycParam.tycId = item.id
      this.tycParam.fundFullName = fundFullName
      fundDetailsByName(this.tycParam).then(res => {
        if (res.msg === 'nofind') {
          this.form.fundFullName = ''
          this.msgError(this.$t('天眼查没有获取到该公司信息!'))
        } else {
          // 基金简称
          this.form.fundName = fundFullName
          // 企业统一社会信用代码
          this.form.creditCode = res.data.creditCode
          // 成立时间
          this.form.foundationDate = res.data.setDate
          // 注册地-省
          this.form.provinceRegistered = res.data.provinceRegistered
          this.form.cityRegistered = res.data.cityRegistered
          if (this.$refs.cityZj?.initCity !== undefined) {
            this.$refs.cityZj.initCity()
            this.$refs.cityZj.initDistrict()
          }
          // 注册区
          this.form.districtRegistered = res.data.registerDistrict
          // 天眼查ID
          this.form.tycId = res.data.tycId
          // 基金logo
          this.form.logoInfo = res.data.logo
          this.msgSuccess(this.$t('已获取工商信息!'))
        }
      })
    },
    // 初始化阶段数据
    initPhaseData() {
      this.getDicts('fund_phase').then(response => {
        for (var i = 0; i < response.data.length; i++) {
          var phaseData = {
            phase: response.data[i].dictValue,
            year: undefined,
            startDate: undefined,
            endDate: undefined
          }
          this.form.fundPhaseList.push(phaseData)
        }
        this.loading = false
      })
    },
    // 删除基金阶段
    delFundPhase(index) {
      this.form.fundPhaseList.splice(index, 1)
    },
    // 添加基金阶段
    addFundPhase() {
      const row = {
        id: undefined,
        phase: undefined,
        year: undefined,
        startDate: undefined,
        endDate: undefined,
        accrualBase: undefined,
        managementFeeRatio: undefined
      }
      if (!(this.form.fundPhaseList instanceof Array)) {
        this.$set(this.form, 'fundPhaseList', [])
      }
      this.$nextTick(() => {
        this.form.fundPhaseList.push(row)
      })
    },
    // 根据期限(年)和起始日期计算结束日期
    yearChange(row, index) {
      // 是否为1开头的正整数
      var reg = /^[1-9]+$/
      // 如果年份是正整数 并且起始日期不为空 就根据起始日期和年份计算结束日期
      if (reg.test(row.year)) {
        if (this.endDateChange(row, index) && row.startDate) {
          const current = Object.assign({}, row)
          var date = new Date(current.startDate)
          date.setFullYear(date.getFullYear() + Number(row.year))
          date.setDate(date.getDate() - 1)
          current.endDate = date
          this.$set(this.form.fundPhaseList, index, current)
        }
      }
    },
    startDateChange(row, index) {
      this.yearChange(row, index)
      this.checkDate(row, index)
    },
    endDateChange(row, index) {
      if (this.checkDate(row, index)) {
        if (index !== 0) {
          const prev = Object.assign({}, this.form.fundPhaseList[index - 1])
          if (prev.endDate) {
            const current = Object.assign({}, this.form.fundPhaseList[index])
            prev.endDate = new Date(prev.endDate)
            prev.endDate.setDate(prev.endDate.getDate() + 1)
            current.startDate = prev.endDate
            // 设置当前行的结束日期
            const date = new Date(current.startDate)
            date.setFullYear(date.getFullYear() + Number(row.year))
            date.setDate(date.getDate() - 1)
            current.endDate = date
            this.$set(this.form.fundPhaseList, index, current)
          }
        }
        return true
      }
      return false
    },
    // 检查日期是否合格
    checkDate(row, index) {
      const current = Object.assign({}, this.form.fundPhaseList[index])
      if (index !== 0) {
        // const prev = Object.assign({}, this.form.fundPhaseList[index - 1])
        // let flag = true
        if (current.startDate && current.endDate && this.compareDate(current.startDate, current.endDate)) {
          this.$message({
            message: this.$t('起始日期不能大于结束日期'),
            type: 'warning'
          })
          current.endDate = undefined
          this.$set(this.form.fundPhaseList, index, current)
          return false
        }
      } else {
        if (current.startDate && current.endDate && this.compareDate(current.startDate, current.endDate)) {
          this.$message({
            message: this.$t('起始日期不能大于结束日期'),
            type: 'warning'
          })
          current.endDate = undefined
          this.$set(this.form.fundPhaseList, index, current)
          return false
        }
      }
      return true
    },
    addManager() {
      console.log('添加管理人')
      this.managerOpen = true
      this.$nextTick(() => {
        this.$refs.gpBaseForm.init(null)
        this.$refs.gpBaseForm.form.type = 'NB'
        this.$refs.gpBaseForm.form.busType = 'MANAGER'
      })
    },
    successSaveManager(data) {
      console.log(data, '管理人已成功添加')
      if (data.busType === 'GP') {
        this.findGpOption()
        this.form.gpIds = [data.id]
      } else {
        this.form.managerId = data.id
      }
    },
    // 比较日期大小
    compareDate(date1, date2) {
      const formatDate1 = new Date(date1)
      const formatDate2 = new Date(date2)
      return formatDate1 > formatDate2
    }
  }
}
</script>
<style type="text/scss" lang="scss" scoped>
.addGLR {
  height: 36px;
  position: absolute;
  right: 30px;
  z-index: 1 !important;
  border: 1px solid #dcdfe6;
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
  background-color: #f5f7fa;
  color: #9e9898;
}
.addGLRText {
  padding: 0 10px;
  cursor: pointer;
  color: inherit;
  text-decoration: none;
  font-size: 14px;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
}
</style>
